package com.immortal.core.module.secure.resolver;

import com.immortal.core.module.secure.anno.EnRequestBody;
import com.immortal.core.module.secure.service.RequestDecoder;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>Title: DecryptHandlerMethodArgumentResolver</p>
 * <p>Description: TODO</p>
 *
 * @author xukk
 * @version 1.0
 * @date 2018/9/4
 */
public class DecryptHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    private RequestDecoder requestDecoder;
    private String decodeParam = "data";

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(EnRequestBody.class) != null;
    }

    public DecryptHandlerMethodArgumentResolver(RequestDecoder requestDecoder, String decodeParam) {
        this.requestDecoder = requestDecoder;
        this.decodeParam = decodeParam;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String data = request.getParameter(decodeParam);
        if (StringUtils.hasText(data)) {
            try {
                data = requestDecoder.decode(data);
            } catch (Exception e) {
                throw new RuntimeException("解密失败");
            }
            return data;
        } else {
            return data;
        }
    }
}